﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace Utils
{
    /// <summary>
    /// 工具类
    /// </summary>
    public class SysUtils
    {
        /// <summary>
        /// 判断对象是否为Int32类型的数字
        /// </summary>
        /// <param name="Expression"></param>
        /// <returns></returns>
        public static bool IsNumeric(object Expression)
        {
            return TypeParse.IsNumeric(Expression);
        }

        /// <summary>
        /// 初始化时间 1900-1-1
        /// </summary>
        public static DateTime InitMinDateTime { get { return Convert.ToDateTime("1900-1-1"); } }

        /// <summary>
        /// 邮箱验证
        /// </summary>
        /// <param name="Expression"></param>
        /// <returns></returns>
        public static bool IsEmail(object Expression)
        {
            System.Text.RegularExpressions.Regex reg = new System.Text.RegularExpressions.Regex("^(\\w)+(\\.\\w+)*@(\\w)+((\\.\\w+)+)$");
            return Expression is String && !string.IsNullOrEmpty(Expression.ToString()) && reg.IsMatch(Expression.ToString());
        }

        /// <summary>
        /// 获取客户机的ＩＰ
        /// </summary>
        /// <returns></returns>
        public static string GetClientIP(System.Web.HttpContext page)
        {

            HttpRequest Request = page.Request;
            HttpServerUtility Server = page.Server;

            /*穿过代理服务器取远程用户真实IP地址：*/
            if (Request.ServerVariables["HTTP_VIA"] != null && Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
                return Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            else
                return Request.ServerVariables["REMOTE_ADDR"].ToString();
        }

        /// <summary>
        /// /获取服务器IP
        /// </summary>
        /// <returns></returns>
        public static string GetServerIP()
        {
            string hostName = System.Net.Dns.GetHostName();
            System.Net.IPAddress[] ips = System.Net.Dns.GetHostAddresses(hostName);

            string getIp = "127.0.0.1";
            foreach (var ip in ips)
            {
                if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                {
                    return ip.ToString();
                }
            }
            return getIp;
        }



        /// <summary>
        /// ip地址验证
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static bool IsIPAddress(string ip)
        {

            if (string.IsNullOrEmpty(ip) || ip.Length < 7 || ip.Length > 15) return false;

            string regformat = @"^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$";

            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);

            return regex.IsMatch(ip);

        }
        /// <summary>
        /// email地址格式验证
        /// </summary>
        /// <param name="email">email</param>
        /// <returns>是否email地址格式</returns>
        public static bool IsEmail(string email)
        {
            Regex reg = new Regex("^([a-zA-Z0-9_\\.\\-])+\\@(([a-zA-Z0-9\\-])+\\.)+([a-zA-Z0-9]{2,4})+$");
            return reg.IsMatch(email);
        }
        /// <summary>
        /// 手机号码格式验证
        /// </summary>
        /// <param name="phone">手机号</param>
        /// <returns>是否手机号码</returns>
        public static bool IsPhoneNum(string phone)
        {
            Regex reg = new Regex("^[0-9]{11}$");
            return reg.IsMatch(phone);
        }

        public static string GetWebContent(string url)
        {
            //System.GC.Collect();

            System.Net.HttpWebRequest req = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);

            req.Method = "GET";

            System.IO.Stream stream = null;

            System.IO.StreamReader sr = null;
            try
            {
                //req.Timeout=
                System.Net.WebResponse response = req.GetResponse();
                stream = response.GetResponseStream();

                sr = new System.IO.StreamReader(stream);

                string str = sr.ReadToEnd();

                response.Close();

                response = null;

                return str;
            }
            finally
            {
                if (stream != null)
                    stream.Close();

                if (sr != null)
                    sr.Close();

                if (req != null)
                {
                    req.Abort();
                    req = null;
                }


            }

        }



        /// <summary>
        /// 返回字节数
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int GetStringByteLen(string str)
        {
            if (string.IsNullOrEmpty(str))
                throw new ArgumentNullException("str");

            return Encoding.Default.GetByteCount(str);
        }

        /// <summary>
        /// 判断某个ip是否存在于某个ip组合或者ip段中（ip之前以，号隔开，ip段为开始ip-结束ip）
        /// 如：127.0.0.1,192.168.200.0-192.168.200.255
        /// </summary>
        /// <param name="checkIp">要检查的ip</param>
        /// <param name="allIps">ip组合或者ip段</param>
        /// <returns>某个ip是否存在于某个ip组合或者ip段中</returns>
        public static bool HaveThisIP(string checkIp, string allIps)
        {
            //如果不是ip，则返回错误
            if (!IsIPAddress(checkIp))
            {
                return false;
            }
            string[] sIps = allIps.Split(',');
            if (sIps.Count() == 0)
            {
                return false;
            }
            if (sIps.Contains(checkIp))
            {
                return true;
            }
            foreach (string ip in sIps)
            {
                if (ip.Contains("-"))
                {
                    if (HaveThisIpInBlock(checkIp, ip))
                    {
                        return true;
                    }
                }
            }
            return false;
        }
        /// <summary>
        /// 查看某个ip是否属于某个ip段
        /// </summary>
        /// <param name="checkIp"></param>
        /// <param name="ipBlock"></param>
        /// <returns></returns>
        private static bool HaveThisIpInBlock(string checkIp, string ipBlock)
        {
            string[] ips = ipBlock.Split('-');
            if (ips.Count() != 2)
            {
                return false;
            }
            string[] sStart = ips[0].Split('.');
            string[] sEnd = ips[1].Split('.');
            string[] sCheck = checkIp.Split('.');
            for (int i = 0; i < 4; i++)
            {
                if (sStart[i] != sEnd[i])
                {
                    if (Convert.ToInt32(sCheck[i]) >= Convert.ToInt32(sStart[i]) && Convert.ToInt32(sCheck[i]) <= Convert.ToInt32(sEnd[i]))
                    {
                        return true;
                    }
                    return false;
                }
                else if (sCheck[i] != sEnd[i])
                {
                    return false;
                }
            }
            return true;
        }

    }
}
